﻿using Liju.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LiJu
{
    public partial class UserSwitch : Form
    {

        /// <summary>
        /// 返回用户名
        /// </summary>
        public string ReturnValue { get; set; }


        /// <summary>
        /// 返回用ID
        /// </summary>
        public string ReturnID { get; set; }

        /// <summary>
        /// 操作类型{1：切换登录，2：更换密码}
        /// </summary>
        public int OperateType { get; set; }


        public UserSwitch()
        {
            InitializeComponent();
            this.AcceptButton = BtnLogin;

        }

        private void UserSwitch_Load(object sender, EventArgs e)
        {

            //根据操作类型，切换页面显示文本
            LblMs.Text = OperateType == 1 ? "切换用户" : "修改密码";
            BtnLogin.Text = OperateType == 1 ? "登录" : "确定";

            LblOne.Text = OperateType == 1 ? "用户名：" : "原密码：";
            LblTwo.Text = OperateType == 1 ? "密码：" : "新密码：";

            //判断第一个输入框
            TbxOne.UseSystemPasswordChar = OperateType != 1;

            if (OperateType == 1)
            {
                string isMesUserLogin = ConfigurationManager.AppSettings["IsMesUserLogin"];
                string isLocalUserLogin = ConfigurationManager.AppSettings["IsLocalUserLogin"];
                if (isMesUserLogin == "1" && isLocalUserLogin == "1")
                {
                    if (MessageBox.Show("当前已登录过MES用户，是否自动进行切换？", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {

                        // 写入配置
                        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        config.AppSettings.Settings["IsLocalUserLogin"].Value = "0";

                        config.Save(ConfigurationSaveMode.Modified);

                        // 强制刷新配置
                        ConfigurationManager.RefreshSection("appSettings");

                        this.Close();   
                    }
                }
            }
        }


        private void BtnLogin_Click(object sender, EventArgs e)
        {
            //文本框1
            string tbx1 = TbxOne.Text.Trim();

            //文本框2
            string tbx2 = TbxTwo.Text.Trim();

            if (!string.IsNullOrWhiteSpace(tbx1) && !string.IsNullOrWhiteSpace(tbx2))
            {

                string parm1 = OperateType == 1 ? tbx1 : ReturnValue;
                string parm2 = OperateType == 1 ? tbx2 : tbx1;


                //校验用户ID、用户名、用户密码是否正常

                var result = PageDataDto.SystemParentMenuRoleInfo(parm1, EncryptionHelper.Encrypt(parm2));

                //判断是否符合条件，并且密码要大于等于6位
                if (result.Id > 0 && tbx2.Length >= 6)
                {

                    if (OperateType == 1)
                    {
                        if (result.State && result.RoleCount > 0 && result.RoleState)
                        {

                            ReturnID = result.UserID;
                            ReturnValue = result.UserName;

                            // 写入配置
                            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                            config.AppSettings.Settings["UserID"].Value = result.UserID;
                            config.AppSettings.Settings["UserName"].Value = result.UserName;   // 写入配置
                            config.AppSettings.Settings["IsLocalUserLogin"].Value = "1";




                            config.Save(ConfigurationSaveMode.Modified);

                            // 强制刷新配置
                            ConfigurationManager.RefreshSection("appSettings");

                            //MessageBox.Show("切换用户成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else if (result.RoleCount == 0)
                        {
                            MessageBox.Show("当前切换用户不存在权限菜单，请联系管理员进行添加！", "异常信息 ！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else if (!result.RoleState)
                        {
                            MessageBox.Show("当前登录用户所属角色已失效，请联系管理员！", "异常信息 ！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else if (!result.State)
                        {
                            TbxOne.Text = "";
                            TbxTwo.Text = "";
                            TbxOne.Focus();
                            MessageBox.Show("当前登录用户已被禁用，请联系管理员进行启用！", "异常信息 ！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }

                    //更新密码
                    if (OperateType == 2)
                    {
                        string sql = string.Format(@"update usermanager set `Password`='{0}' where UserName='{1}' and `Password`='{2}'", EncryptionHelper.Encrypt(tbx2), parm1, EncryptionHelper.Encrypt(parm2));
                        Db.DalMySQL.ExecuteNonQuery(sql);
                        MessageBox.Show("密码修改成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }

                    //关闭当前页面
                    this.Close();


                }
                else
                {

                    string msg1 = OperateType == 1 ? "请重新输入账号和密码！" : "旧密码输入错误，或新密码不足6位数，请重做输入！";
                    string msg2 = OperateType == 1 ? "账号或密码输入错误！" : "密码修改失败！";
                    ResultMessageInfo(msg1, msg2, OperateType);


                    TbxOne.Text = "";
                    TbxTwo.Text = "";
                    TbxOne.Focus();
                }

            }

            else
            {
                string msg1 = OperateType == 1 ? "请重新输入账号和密码！" : "请重新输入密码！";
                string msg2 = OperateType == 1 ? "账号或密码不能为空！" : "旧密码或新密码不能为空！";
                ResultMessageInfo(msg1, msg2, OperateType);

                TbxOne.Focus();
                if (!string.IsNullOrWhiteSpace(tbx1))
                {
                    TbxTwo.Focus();
                }


            }
        }


        /// <summary>
        /// 返回页面消息提示
        /// </summary>
        /// <param name="msg1">消息</param>
        /// <param name="msg2">标题</param>
        /// <param name="type"></param>
        public void ResultMessageInfo(string msg1, string msg2, int type)
        {

            MessageBox.Show(msg1, msg2, MessageBoxButtons.OK, MessageBoxIcon.Error);

            //后续添加操作日志

        }

        private void TbxOne_KeyPress(object sender, KeyPressEventArgs e)
        {

            if (OperateType == 1)
            {
                if (e.KeyChar >= '0' && e.KeyChar <= '9' || Char.IsLetter(e.KeyChar))//输入1-8位数字或字母
                {
                    if (TbxOne.Text.Length <= 11)
                    {
                        e.Handled = false;
                    }
                    else if (TbxOne.SelectionLength > 1)
                    {
                        e.Handled = false;//选择多个
                    }
                    else
                    {
                        e.Handled = true;
                    }
                }

                //e.KeyChar == '.' ||
                else if (e.KeyChar == (char)Keys.Return) //Tab或回车键
                {
                    e.Handled = true;
                    SendKeys.Send("{TAB}");
                }
                else if (e.KeyChar == '\b' || (int)e.KeyChar == 7)
                    e.Handled = false;//删除
                else
                    e.Handled = true;
            }
            else
            {
                if (e.KeyChar >= '0' && e.KeyChar <= '9' || Char.IsLetter(e.KeyChar) || Char.IsPunctuation(e.KeyChar))//输入1-8位数字或字母
                {
                    if (TbxOne.Text.Length <= 15)
                    {
                        e.Handled = false;
                    }
                    else if (TbxOne.SelectionLength > 1)
                    {
                        e.Handled = false;//选择多个
                    }
                    else
                    {
                        e.Handled = true;
                    }
                }
                else if (e.KeyChar == (char)Keys.Return) //Tab或回车键
                {
                    e.Handled = true;
                    SendKeys.Send("{TAB}");
                }
                else if (e.KeyChar == '\b' || (int)e.KeyChar == 7)
                    e.Handled = false;//删除
                else
                    e.Handled = true;
            }

        }

        private void TbxTwo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar >= '0' && e.KeyChar <= '9' || Char.IsLetter(e.KeyChar) || Char.IsPunctuation(e.KeyChar))//输入1-8位数字或字母
            {
                if (TbxTwo.Text.Length <= 15)
                {
                    e.Handled = false;
                }
                else if (TbxTwo.SelectionLength > 1)
                {
                    e.Handled = false;//选择多个
                }
                else
                {
                    e.Handled = true;
                }
            }
            else if (e.KeyChar == (char)Keys.Return) //Tab或回车键
            {
                e.Handled = true;
                SendKeys.Send("{TAB}");
            }
            else if (e.KeyChar == '\b' || (int)e.KeyChar == 7)
                e.Handled = false;//删除
            else
                e.Handled = true;
        }
    }
}
